package com.wanmei.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import com.wanmei.exception.WanmeiException;
import com.wanmei.mapper.ActiveInfoMapper;
import com.wanmei.mapper.RoleMapper;
import com.wanmei.mapper.UserMapper;
import com.wanmei.pojo.ActiveInfo;
import com.wanmei.pojo.Exception_Msg;
import com.wanmei.pojo.User;
import com.wanmei.pojo.UserList;
import com.wanmei.util.MD5;
import com.wanmei.util.MailUtil;
import com.wanmei.util.VolidatorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


@Service("UserService")
public class UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ActiveInfoMapper activeInfoMapper;
    @Autowired
    private RoleMapper roleMapper;
    /**
     * 通过输入的用户名从数据库中获取用户的相关信息
     *
     * @param username
     * @return
     */
    public User getUserByUserName(String username) {
        return userMapper.getUserByUserName(username);
    }

    public int checkUsernameByUsername(String username) {
        return userMapper.getUserNameByUserName(username);
    }

    public int insertUserInfo(User user, String rePassword) throws WanmeiException {

        //检查是否直接注册空账号
        if (user.getUsername() == null || user.getUsername() == "") {
            throw new WanmeiException(Exception_Msg.ERROR_100001);
        }
        //检查密码是否符合规范，重新输入密码有没有出现错误。
        if (!VolidatorUtil.isPassword(user.getPassword())) {
            throw new WanmeiException(Exception_Msg.ERROR_100002);
        }
        if (rePassword == null || rePassword == "") {
            throw new WanmeiException(Exception_Msg.ERROR_100003);
        }
        if (!user.getPassword().equals(rePassword)) {
            throw new WanmeiException(Exception_Msg.ERROR_100004);
        }
        //检查邮箱
        if (!VolidatorUtil.isEmail(user.getEmail())) {
            throw new WanmeiException(Exception_Msg.ERROR_100007);
        }
        int isReEmail = userMapper.checkEmail(user.getEmail());
        if (isReEmail > 0) {
            throw new WanmeiException(Exception_Msg.ERROR_100112);
        }
        Date createTime = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowTime = simpleDateFormat.format(createTime);
        user.setAddtime(nowTime);
        user.setModifytime(nowTime);
        user.setPassword(MD5.md5(user.getPassword()));
        return userMapper.insertSelective(user);
    }

    /**
     * 发送邮件的service
     *
     * @param email
     * @param type
     * @return
     * @throws WanmeiException
     * @throws ParseException
     * @throws MessagingException
     */
    public int saveEmailActiveInfo(String email, String type) throws WanmeiException, ParseException, MessagingException {

        //邮箱验证步骤
        if (email == null || email == "") {
            throw new WanmeiException(Exception_Msg.ERROR_100006);
        }
        if (!VolidatorUtil.isEmail(email)) {
            throw new WanmeiException(Exception_Msg.ERROR_100007);
        }
        int hasUser = userMapper.checkEmail(email);
        if (hasUser <= 0) {
            throw new WanmeiException(Exception_Msg.ERROR_100005);
        }
        //防止恶意刷新页面不断发送邮箱
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss");
        String nowTime = format.format(date);

        ActiveInfo info = activeInfoMapper.getInfoByEmail(email, type);
        if (info != null) {
            String createTime = info.getActiveCreatetime();
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date d1 = df.parse(nowTime);
            Date d2 = df.parse(createTime);
            long d = d1.getTime() - d2.getTime();
            long twoMin = d / (1000 * 60 * 2);
            System.out.println("两分钟内时间：" + twoMin);
            if (twoMin == 0) {
                throw new WanmeiException(Exception_Msg.ERROR_100013);
            }
        }
        int incode = (int) (Math.random() * 10000);
        String text = Integer.toString(incode);
        MailUtil mailUtil = new MailUtil();
        mailUtil.sendMail(email, text);
        ActiveInfo info1 = new ActiveInfo();
        info1.setActiveCount(0);
        info1.setActiveCreatetime(nowTime);
        info1.setActiveStatus(1);
        info1.setUserEmail(email);
        info1.setActiveType(type);
        info1.setActiveCode(text);
        int isUpdate = 0;
        if (info == null) {
            isUpdate = activeInfoMapper.insertSelective(info1);
        } else {
            isUpdate = activeInfoMapper.updateActiveInfo(info1);
        }
        return isUpdate;
    }

    /**
     * 校验验证码
     *
     * @param
     * @return
     * @throws WanmeiException
     * @throws ParseException
     */
    public int checkActiveInfoByCode(String email, String incode, String type,String password,String rePassword) throws WanmeiException, ParseException {
        //先验证邮箱
        if (email == null || email == "") {
            throw new WanmeiException(Exception_Msg.ERROR_100006);
        }
        if (!VolidatorUtil.isEmail(email)) {
            throw new WanmeiException(Exception_Msg.ERROR_100007);
        }

        if (password == null | password == "") {
            throw new WanmeiException(Exception_Msg.ERROR_100008);
        }
        if (rePassword == "" || rePassword == null) {
            throw new WanmeiException(Exception_Msg.ERROR_100003);
        }
        if (!VolidatorUtil.isPassword(password)) {
            throw new WanmeiException(Exception_Msg.ERROR_100002);
        }
        if (!password.equals(rePassword)) {
            throw new WanmeiException(Exception_Msg.ERROR_100004);
        }
        ActiveInfo activeInfo = activeInfoMapper.getInfoByEmail(email, type);
        if (activeInfo == null) {
            throw new WanmeiException(Exception_Msg.ERROR_100009);
        }
        //是否 为空？ 正确？过时
        if (incode == null) {
            throw new WanmeiException(Exception_Msg.ERROR_100010);
        }
        if (!incode.equals(activeInfo.getActiveCode())) {
            activeInfoMapper.addCountByEmail(email, type);
            throw new WanmeiException(Exception_Msg.ERROR_100011);
        }
        if (activeInfo.getActiveCount() > 5) {
            activeInfoMapper.deleteByEmailAndType(email, type);
            throw new WanmeiException(Exception_Msg.ERROR_100101);
        }
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowTime = format.format(date);
        String createTime = activeInfo.getActiveCreatetime();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d1 = df.parse(nowTime);
        Date d2 = df.parse(createTime);
        long d = d1.getTime() - d2.getTime();
        System.out.println("时间是：" + d);
        long hours = d / (1000 * 60 * 30);
        if (hours > 0) {
            throw new WanmeiException(Exception_Msg.ERROR_100012);
        }
        activeInfoMapper.deleteByEmailAndType(email, type);
        User user = new User();
        user.setPassword(MD5.md5(password));
        user.setEmail(email);
        user.setModifytime(nowTime);
        return userMapper.updatePwdByEmail(user);

    }

        /**
         * 分页模糊查询
         *
         * @param pageNum
         * @param pageSize
         * @param likeValue
         * @param
         * @return
         */
    public PageInfo<UserList> getLikeUserInfo(int pageNum, int pageSize, String likeValue) {
        PageHelper.startPage(pageNum, pageSize);
        UserList userList = new UserList();
        List<UserList> list;
        PageInfo<UserList> info;
        if (likeValue == null || likeValue == "") {
            list = userMapper.selectUserListAll();
        } else {
            list = userMapper.selectFuzzyAll(likeValue);
            //过会记得实现  isfuzzy
        }
        info = new PageInfo<>(list);
        return info;
    }
    /**
     * 分页模糊降序查询
     */

    public PageInfo<UserList> getLikeUserInfoDesc(int pageNum, int pageSize, String likeValue) {
        String order = "uid DESC";
        PageHelper.startPage(pageNum, pageSize,order);
        UserList userList = new UserList();
        List<UserList> list;
        PageInfo<UserList> info;
        if (likeValue == null || likeValue == "") {
            list = userMapper.selectUserListAll();
        } else {
            list = userMapper.selectFuzzyAll(likeValue);
            //过会记得实现  isfuzzy
        }
        info = new PageInfo<>(list);
        return info;
    }
    /**
     * 删除用户
     */
    public int deleteUserByuid(int uid){
        return userMapper.deleteUserByuid(uid);
    }
    /**
     * 编辑用户跳出模态框
     */
    public UserList getUserListByuid(int uid){
        return userMapper.getUserListByuid(uid);
    }

    /**
     * 编辑用户，修改用户信息
     */

    public int updateByUser(UserList userList){
        int rid =roleMapper.getRoleIdByRoleName(userList.getRoleName());
        User user =new User();
        user.setEmail(userList.getEmail());
        user.setUsername(userList.getUsername());
        if (userList.getPassword()!=null&&userList.getPassword()!="") {
            user.setPassword(MD5.md5(userList.getPassword()));
        }
        user.setRelname(userList.getRelName());
        user.setRid(rid);
        user.setTel(userList.getTel());
        Date date= new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowTime = format.format(date);
        user.setModifytime(nowTime);
        return userMapper.updateByUser(user);
    }

    /**
     * 管理员添加用户！
     * @param user
     * @param addUser
     * @return
     * @throws WanmeiException
     */
    public int addUserInfo(User user, String addUser) throws WanmeiException {

        //检查是否直接注册空账号
        if (user.getUsername() == null || user.getUsername() == "") {
            throw new WanmeiException(Exception_Msg.ERROR_100001);
        }
        //检查密码是否符合规范，重新输入密码有没有出现错误。
        if (!VolidatorUtil.isPassword(user.getPassword())) {
            throw new WanmeiException(Exception_Msg.ERROR_100002);
        }
        //检查邮箱
        int isReEmail = userMapper.checkEmail(user.getEmail());
        if (isReEmail > 0) {
            throw new WanmeiException(Exception_Msg.ERROR_100112);
        }
        if (!VolidatorUtil.isEmail(user.getEmail())){
            throw new WanmeiException(Exception_Msg.ERROR_100007);
        }
        if (!VolidatorUtil.isMobile(user.getTel())){
            throw new WanmeiException(Exception_Msg.ERROR_100111);
        }
        Date createTime = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowTime = simpleDateFormat.format(createTime);
        user.setAddtime(nowTime);
        user.setModifytime(nowTime);
        user.setPassword(MD5.md5(user.getPassword()));
        return userMapper.insertSelective(user);
    }
}
